﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Group16.Class_Library;
using System.Data.SqlClient;
namespace Group16.Controller
{
    public partial class SaleForm : baseSearchForm
    {
        public List<Device> SoldDevices = new List<Device>();
        public Customer CustomInfomation;
        //public InvoiceDetails Detail;
        public Invoice SaleInvoice;
        public SaleForm()
        {
            InitializeComponent();
            Setting();
            SetDataSource();
        }
        private void Setting()
        {

            try
            {
                string comText = "Select Name from Devices";
                SqlDataReader read = (SqlDataReader)DataBaseInteraction.ExecuteCommand(comText, 2);
                while (read.Read())
                {
                    string s = read.GetString(0);
                    cmbKeyWord.AutoCompleteCustomSource.Add(s);
                }
            }
            catch (SqlException se)
            {
                MessageBox.Show("Problem in interaction with database" + se.Message);
            }
            finally
            {
                DataBaseInteraction.Connection.Close();
            }
        }
        protected override void Search()
        {
            string mess = cmbKeyWord.Text;
            if (String.IsNullOrEmpty(mess))
            {
                lbMessage.Text = "Please! Enter device's name needing searching!";
            }
            else
                lbMessage.Text = "";
            DeviceManager Manager = new DeviceManager();
            Manager.SearchDevices(mess);
            gridDetail.DataSource = Manager.Devices;
        }

        private void SetDataSource()
        {
            gridDetail.SuspendLayout(); //tam thoi tri hoan
            gridDetail.AutoGenerateColumns = false;
            gridDetail.AlternatingRowsDefaultCellStyle.BackColor = Color.DarkCyan;

            DataGridViewCheckBoxColumn chkCol = new DataGridViewCheckBoxColumn();
            chkCol.DataPropertyName = "Sold";
            chkCol.Name = "Sold";
            chkCol.Width = 40;
            
            DataGridViewColumn field = new DataGridViewTextBoxColumn();
            field.DataPropertyName = "Field";
            field.Name = "Field";
            field.ReadOnly = true;
            DataGridViewColumn title = new DataGridViewTextBoxColumn();
            title.DataPropertyName = "Title";
            title.Name = "Title";
            title.ReadOnly = true;
            DataGridViewColumn series = new DataGridViewTextBoxColumn();
            series.DataPropertyName = "Series";
            series.Name = "Series";
            series.ReadOnly = true;
            DataGridViewColumn name = new DataGridViewTextBoxColumn();
            name.DataPropertyName = "Name";
            name.Name = "Name";
            name.ReadOnly = true;
            DataGridViewColumn cost = new DataGridViewTextBoxColumn();
            cost.DataPropertyName = "Cost";
            cost.Name = "Cost";
            cost.ReadOnly = true;
            DataGridViewColumn origin = new DataGridViewTextBoxColumn();
            origin.DataPropertyName = "Origin";
            origin.Name = "Origin";
            cost.ReadOnly = true;
            DataGridViewColumn warranty = new DataGridViewTextBoxColumn();
            warranty.DataPropertyName = "Warranty";
            warranty.Name = "Warranty";
            cost.ReadOnly = true;
            DataGridViewColumn disciption = new DataGridViewTextBoxColumn();
            disciption.DataPropertyName = "Discription";
            disciption.Name = "Discription";
            disciption.ReadOnly = true;

            gridDetail.Columns.AddRange(new DataGridViewColumn[] { chkCol, series, name, cost, field, title, origin, warranty, disciption });
            gridDetail.ResumeLayout();
        }

        private void gridDevices_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (gridDetail.Columns[e.ColumnIndex].Name == "Sold")
            {
                DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)gridDetail.Rows[e.RowIndex].Cells["Sold"];
                chk.Value = !(bool)chk.Value;
            }
        }
        private void Make()
        {
            if (SoldDevices.Count() > 0)
            {
                
                using (CustomerInfoForm custom = new CustomerInfoForm())
                {
                    DialogResult result = custom.ShowDialog();
                    if (result != System.Windows.Forms.DialogResult.OK)
                    {
                        MessageBox.Show("Can not make out an invoice without custom infomation");
                        return;
                    }
                    CustomInfomation = custom.Customer;
                    CustomInfomation.LogData();

                    //Log invoice to database
                    SaleInvoice = new Invoice();
                    SaleInvoice.DateMade = DateTime.Now;
                    string invoiceCode = Invoice.GetInvoiceCode();
                    if(invoiceCode == null)
                        return;
                    SaleInvoice.InvoiceCode = invoiceCode;
                    SaleInvoice.Total = GetTotal();
                    SaleInvoice.LogData();

                    //Log invoice details to database
                    InvoiceDetails Detail = new InvoiceDetails();
                    Detail.CustomerCode = CustomInfomation.Code;
                    Detail.InvoiceCode = SaleInvoice.InvoiceCode;
                    foreach (Device d in SoldDevices)
                    {
                        Detail.DevicesCodes.Add(d.Series);
                    }
                    Detail.LogData();

                    //Set Sold in database to true to indicate that these item have been sold
                    foreach (Device d in SoldDevices)
                    {
                        SetDeviceSold(d.Series, true);
                    }
                    PrintSupport.PrintPreview();
                    
                    SoldDevices.Clear();
                    gridDetail.DataSource = null;
                    //TODO:gridDevices.Rows.Clear();

                }
            }
            else
                MessageBox.Show("Please! Choose items to sell");
        }
        /// <summary>
        /// Returns a valid invoice code to  insert into database
        /// </summary>
        /// <returns></returns>
        
        /// <summary>
        /// Return total cost for invoice
        /// </summary>
        /// <returns></returns>
        private int GetTotal()
        {
            int total = 0;
            foreach (Device d in SoldDevices)
            {
                total += d.Cost;
            }
            return total;
        }
        /// <summary>
        /// Clear all item have been chosen
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void ClearData()
        {
            foreach (Device d in SoldDevices)
                SetDeviceSold(d.Series, false);
            SoldDevices.Clear();
            gridDetail.DataSource = null;
        }
        /// <summary>
        /// Set value for sold column in database to indicate the  item have been sold or have not
        /// </summary>
        /// <param name="series"></param>
        /// <param name="isSell"></param>
        private void SetDeviceSold(string series, bool isSell)
        {
            try
            {
                string comText;
                if (isSell)
                    comText = "update Devices Set Sold = 'true' Where Series = '" + series+"'";
                else
                    comText = "update Devices Set Sold = 'false' Where Series = '" + series + "'";
                DataBaseInteraction.ExecuteCommand(comText, 1);
            }
            catch (SqlException se)
            {
                MessageBox.Show("Problem in interaction with database " + se.Message);
            }
            finally
            {
                DataBaseInteraction.Connection.Close();
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            AddToSell();
            //gridDevices.Rows.Clear();
        }
        /// <summary>
        /// Add all the items have been chosen to list selling
        /// </summary>
        private void AddToSell()
        {
            foreach (DataGridViewRow row in gridDetail.Rows)
            {
                DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)row.Cells["Sold"];
                if ((bool)cell.FormattedValue)
                {
                    string series = (string)row.Cells["Series"].Value;

                    Device d = new Device();
                    d.Sold = true;
                    d.Field = (string)row.Cells["Field"].Value;
                    d.Series = series;
                    d.Name = (string)row.Cells["Name"].Value;
                    d.Cost = (int)row.Cells["Cost"].Value;
                    d.Title = (string)row.Cells["Title"].Value;
                    d.Warranty = (int)row.Cells["Warranty"].Value;
                    d.Origin = (string)row.Cells["Origin"].Value;
                    d.Discription = (string)row.Cells["Discription"].Value;
                    ///Khong duoc ham contain?
                    foreach (Device device in SoldDevices)
                        if (String.Compare(d.Series, device.Series) == 0)
                            return;
                    SoldDevices.Add(d);
                }
            }
        }

        private void btnMake_Click(object sender, EventArgs e)
        {
            Make();
        }
        

    }
}
